package cn.com.ylpw.web.order.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.ylpw.spring.SpringController;
import cn.com.ylpw.utils.StringUtils;
import cn.com.ylpw.web.enums.CardInfo.CardResult;
import cn.com.ylpw.web.order.service.IAddressService;
import cn.com.ylpw.web.order.service.OrderService;
import cn.com.ylpw.web.order.service.payService;
import cn.com.ylpw.web.order.service.saveOrderService;
import cn.com.ylpw.web.util.DateUtils;
import cn.com.ylpw.web.util.ServletUtil;
import cn.com.ylpw.web.util.StringUtil;

@Controller("ajaxContrller")
@RequestMapping("/ajax")
public class AjaxController extends SpringController {
	
	public final Logger log= LoggerFactory.getLogger(getClass());

	
	@Autowired
	@Qualifier("orderService")
	private OrderService orderService;
	@Autowired
	@Qualifier("addressService")
	private IAddressService addressService;
	
	@Autowired
	@Qualifier("payService")
	private payService payService;	
	@Autowired
	@Qualifier("saveOrderService")
	private saveOrderService saveOrderService;
	/**
	 * @description 功能描述: 加载省-城市-区信息
	 * @author      作 者: 于旺
	 * @param       参数:
	 * @return      返回类型: Map<String,Object>
	 * @createdate  建立日期: 2015年10月19日11:09:07
	 */
	@RequestMapping(value = "/loadRangeNew")
	public @ResponseBody Map<String, Object> loadRange(String type, Integer typeId) {
		log.info("ajax加载:省-城市-区-区域信息");
		int ajaxResponse = 1; // ajax响应成功标识
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("type", type);
		params.put("typeId", typeId);
		List<Map<String, Object>> rangeList = new ArrayList<Map<String, Object>>();
		try {
			if (StringUtils.isNotBlank(type)) {
				if(type.equals("provinces")){
					rangeList = addressService.findAllProvinces(params);
				}else if(type.equals("cities")){
					rangeList =  addressService.findAllCitys(params);
				}else if(type.equals("areas")){
					rangeList =  addressService.findAllAreas(params);
				}else if(type.equals("codes")){
					/*rangeList  = addressService.findCodeNameIsNotNull(params);
					 Map<String,Object> map = new HashMap<String,Object>();
					 if(rangeList != null && rangeList.size() != 0){
						 map.put("isShow", 1);
						 rangeList.add(map);
					 }else{
						 rangeList = addressService.findCodeNameIsNull(params);
						 map.put("isShow", 2);
						 rangeList.add(map);
					 }*/
					params.put("areaId", typeId);
					rangeList  = addressService.findAllCodes(params);
				}else {
					//传入的type格式有问题
					ajaxResponse = 2;
					result.put("ajaxResponse", ajaxResponse);
					return result;
				}
				result.put("rangeList", rangeList);
			}			
		} catch (Exception e) {
			log.warn("加载省-城市-区信息失败{}",params,e);
			result.put("ajaxResponse", ajaxResponse);
			return result;
		}
		ajaxResponse = 1;
		result.put("ajaxResponse", ajaxResponse);
		return result;
	}
	/**
	 * @description 功能描述: 计算快递费用
	 * @author      作          者: 刘伟
	 * @param       参          数:
	 * @return      返回类型: Map<String,Object>
	 * @createdate  建立日期: 2013-8-26下午2:13:28
	 */
	@RequestMapping(value = "/getFreightNew" ,method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> getFreight(HttpServletRequest request,HttpSession session) {
		log.info("ajax根据分站id查询分站上门自取相关");
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> freightParams = new HashMap<String, Object>();
		int ajaxResponse = 1; // ajax响应成功标识
		Integer flag = 1; //是否支持货到付款 0不支持 1支持
		Integer areaId = -1;
		Integer cityId =  -1;
		Integer codeId =  -1;
		Integer provinceId = -1;
		Integer fconfigId = -1;
		if (null != request.getParameter("cusAddressId") && !StringUtil.isEmpty(request.getParameter("cusAddressId").toString())) {
			Integer cusAddressId = Integer.valueOf(request.getParameter("cusAddressId").toString());
			freightParams.put("addressIdCustomersId", cusAddressId);
			
			freightParams.put("customersId", ServletUtil.getCustomerId(session));
			Map<String, Object> cusaddres = addressService.findAddressCustomerById(freightParams);
			provinceId = Integer.parseInt(cusaddres.get("provinceId").toString());
			cityId = Integer.parseInt(cusaddres.get("cityId").toString());
			areaId = Integer.parseInt(cusaddres.get("areaId").toString());
			codeId =Integer.parseInt(cusaddres.get("codeId").toString());
			
		} else if(null != request.getParameter("provinceId")){
			provinceId = Integer.parseInt(request.getParameter("provinceId").toString());// 获得收货人地址省份id
			cityId = Integer.parseInt(request.getParameter("cityId").toString()); // 获得收获城市id
			areaId = Integer.parseInt(request.getParameter("areaId").toString()); // 获得收获人区id
			codeId = Integer.parseInt(request.getParameter("codeId").toString());// 获得收获区域id
		}
		freightParams.put("provinceId",provinceId);
		freightParams.put("cityId",cityId);
		freightParams.put("areaId",areaId);
		freightParams.put("codeId",codeId);
		//如果收货城市和商品城市不在同一个城市
		if(null != request.getParameter("fconfigId")){
			fconfigId =  Integer.parseInt(request.getParameter("fconfigId"));
			freightParams.put("fconfigId",fconfigId);
			Map<String, Object> fconfig = null;
			List<Map<String, Object>> codeInfo = null;
			try {
				fconfig = orderService.findTfconfig(freightParams);
				codeInfo = addressService.findAllCodes(freightParams);
			} catch (Exception e) {
				log.error("计算快递费用",e);
			}
			if (fconfig == null || codeInfo == null) {
				ajaxResponse = 2;
				result.put("ajaxResponse", ajaxResponse);
				return result;
			}
			Integer productCityId = Integer.parseInt(fconfig.get("cityId").toString());
			if(productCityId != -1 && !productCityId.toString().equals(cityId.toString())){
				flag = 0;
			}
			if(null != codeInfo && codeInfo.size() > 0 && codeInfo.size() == 1){
				Map<String, Object> codeMap = codeInfo.get(0);
				String supporthdfk = codeMap.get("supporthdfk").toString();
				String status =  codeMap.get("status").toString();
				if(supporthdfk.equals(String.valueOf(0)) || status.equals(String.valueOf(0))){
					flag = 0;
				}
			}else if(codeInfo.size() > 1){
				for(Map<String, Object> codeMap : codeInfo){
					String supporthdfk = codeMap.get("supporthdfk").toString();
					String status =  codeMap.get("status").toString();
					if(codeMap.get("codeId").toString().equals(codeId.toString()) && (supporthdfk.equals(String.valueOf(0)) || status.equals(String.valueOf(0)))){
						flag = 0;
						break;
					}
				}
			}
		}
		Double subTotal = Double.parseDouble(request.getParameter("subTotal"));// 打完折后的金额
		freightParams.put("subTotal", subTotal);
		//计算快递费用，调用规则引擎
		try{
			Map<String, Object> transportationFee = this.transportationFee(freightParams);
			result.put("transportFee", transportationFee.get("rangeprice"));
		}catch (Exception e) {
			log.error("计算快递费用出错,{},默认快递费22",freightParams,e);
			result.put("transportFee", 22.0);
		}
		result.put("flag", flag);
		result.put("ajaxResponse", ajaxResponse);
		return result;
	}	
	
	/**
	 * 运费计算（快递配送、上门自取、电子票）
	 * @description 
	 * @author  邓军
	 * @param orders
	 * @return （快递配送、上门自取、电子票）三种配送运费 的Map
	 * @createdate  2013-7-24上午11:08:41
	 */
	public Map<String, Object> transportationFee(Map<String, Object> freightParams)
	{
		
		//查询分站限制
		Map<String, Object> tFconfig = null;
		List<Map<String, Object>> codes = null;
		try {
			freightParams.put("fconfigId", Integer.valueOf(freightParams.get("fconfigId").toString()));
			freightParams.put("areaId", Integer.valueOf(freightParams.get("areaId").toString()));
			tFconfig = orderService.findTfconfig(freightParams);
			codes = addressService.findAllCodes(freightParams);
		} catch (Exception e) {
			//查询出错说明参数有问题
			log.error("计算运费查询地区异常{}",freightParams,e);
		}
		
		//查询配送地址限制
		Double subTotal = Double.parseDouble(freightParams.get("subTotal").toString());//折后总价
		Double rangeprice = 0.0;
		Integer areaId =Integer.parseInt(freightParams.get("areaId").toString());
		Map<String, Object>  tCode = addressService.findCodeById(freightParams);
		
		if(tCode != null){
			Double comparePrice = Double.parseDouble(tCode.get("comparePrice").toString());
			Double lessPrice = Double.parseDouble(tCode.get("lessPrice").toString());
			Double morePrice = Double.parseDouble(tCode.get("morePrice").toString());
			
			if(tCode.get("status").toString().equals("1")){
				if( subTotal < comparePrice)
				{
					rangeprice = lessPrice;
				}
				
				if( subTotal >= comparePrice)
				{
					rangeprice = morePrice;
				}
			}else{
				tCode = codes.get(0);
				if(  subTotal < comparePrice)
				{
					rangeprice = lessPrice;
				}
				
				if( subTotal >= comparePrice)
				{
					rangeprice = morePrice;
				}
			}
		}
			Map<String, Object> map = new HashMap<String, Object>();
			Integer fconfigIdOrder = Integer.parseInt(tFconfig.get("provinceId").toString());//订单所属分站ID
			Integer cityIdOrder = Integer.parseInt(tFconfig.get("cityId").toString());//订单所属城市ID
			
			Integer provinceIdUser = Integer.parseInt(freightParams.get("provinceId").toString());//配送地址所属省份ID
			Integer cityIdUser = Integer.parseInt(freightParams.get("cityId").toString());//配送地址所属城市ID

			
			if(cityIdOrder.intValue() == cityIdUser.intValue())//同城
			{
				
			}
			else//异地
			{
				Map<String, Object> expressfeespecial = addressService.findTexpressFeespecial(freightParams);
				if(expressfeespecial!=null)//特殊快递费
				{
					rangeprice = Double.valueOf(expressfeespecial.get("rangePrice").toString());
				}
				else//异地统一快递费22
				{
					rangeprice = 22.00;
				}
			}
			map.put("rangeprice", rangeprice);
		return map;
	}	
	/**
	 * @description 功能描述: ajax查询现金券的金额
	 * @author      作          者: 刘伟
	 * @param       参          数: cashCouponNo 现金券ID
	 * @param       参          数: productId 商品ID多个商品以","号分隔
	 * @param       参          数: subtotalval 订单金额
	 * @return 返回类型: Map<String,Object>
	 * @createdate 建立日期: 2013-7-12上午11:13:07
	 */
	@RequestMapping(value = "/findCashCoupon")
	public @ResponseBody Map<String, Object> findCashCoupon(HttpServletRequest request) {
		log.info("ajax查询现金券的金额");
		Map<String, Object> cashParams = new HashMap<>();
		
		//判断用户是否已经登录
		//Map<String, Object> customer = LoginUtils.currentUser();
		Map<String, Object> customer = null;
		try {
			customer = orderService.getCustomer(cashParams);
		} catch (Exception e) {
			log.warn("用户未登录,查询现金券{}",cashParams,e);
		}
		
		String cashCouponNo = request.getParameter("cashCouponNo").toString(); //现金券序列号
		String productId = request.getParameter("productId").toString(); 
		String subTotalVal = request.getParameter("subTotalVal").toString();  
		String fconfigId = request.getParameter("fconfigId").toString();  
		Map<String, Object> result = new HashMap<String, Object>();
		cashParams.put("cashCouponNo", cashCouponNo);
		int ajaxResponse = 1; // ajax响应成功标识
		Integer flag = -3;// 初始标识
		Date rightTime = new Date();// 取现在的时间
		try {
			//可重复使用的券会有多条使用记录，这里按时间取最近的一条记录
			Map <String, Object> cashCouponMap = orderService.findCashcouponInfoByNo(cashParams).get(0);
			if (null != cashCouponMap  && cashCouponMap.size() != 0) {
				//0.判断现金券是否为有效
				Integer invalidstatus = Integer.valueOf(cashCouponMap.get("INVALIDSTATUS").toString());
				//现金券无效
				if(0 == invalidstatus){
					flag = 0;   //设置现金券无效标识
					result.put("flag", flag);
					result.put("ajaxResponse", ajaxResponse);
					return result;
				}
				//判断现金券是否支持重复使用
 				Integer isreuse = Integer.valueOf(cashCouponMap.get("ISREUSE").toString());
				Integer tickettype = 0;
				if(null != cashCouponMap.get("TICKETTYPE")){
					tickettype =  Integer.valueOf(cashCouponMap.get("TICKETTYPE").toString());
				}
				//如果不支持重复使用
				if(0 == isreuse){
					//1.判断现金券状态是否为已指派
					Integer cashCouponStatus = Integer.valueOf(cashCouponMap.get("STATUS").toString());
					//如果现金券的状态不是已指派的话
					if(1 != cashCouponStatus && 2 != cashCouponStatus && 1 != tickettype){
						flag = 0;   //设置现金券无效标识
						result.put("flag", flag);
						result.put("ajaxResponse", ajaxResponse);
						return result;
					}
					//2.判断现金券是否已经使用
					if(2 == cashCouponStatus){
						String beUsedTime = new SimpleDateFormat("yyyy-MM-dd").format((DateUtils.parseDate(cashCouponMap.get("USERDATE").toString(),DateUtils.DAY_FROMAT)));// 现金券使用日期
						result.put("beUsedTime", beUsedTime);
						flag = 1;   //设置现金券已经使用标识
						result.put("flag", flag);
						result.put("ajaxResponse", ajaxResponse);
						return result;
					}
				//如果支持重复使用
				}else{
					
					Integer cashCouponStatus = Integer.valueOf(cashCouponMap.get("STATUS").toString());
					//如果现金券的状态不是已指派或者是已经使用的状态的话
					if(0 != cashCouponStatus && 1 != cashCouponStatus && 2 != cashCouponStatus){
						flag = 0;   //设置现金券无效标识
						result.put("flag", flag);
						result.put("ajaxResponse", ajaxResponse);
						return result;
					}
				}
				String endDate="";
				//3.判断现金券是否已经过期
				String enddate1 = cashCouponMap.get("ENDDATE").toString();
				Date enddate = DateUtils.parseDate(enddate1, DateUtils.CURRENTTIME_FORMAT) ;
				
				if(null != cashCouponMap.get("DAYSLIMIT")){
					//礼券限制日期
					Integer daysLimit = Integer.valueOf(cashCouponMap.get("DAYSLIMIT").toString());
					//礼券指派日期
					Date assignedtime = DateUtils.parseDate(cashCouponMap.get("ASSIGNEDTIME").toString(), DateUtils.CURRENTTIME_FORMAT) ;
					Date limitdate = DateUtils.parseDate(DateUtils.getAfterNDay(assignedtime, daysLimit, DateUtils.CURRENTTIME_FORMAT )[daysLimit-1], DateUtils.CURRENTTIME_FORMAT) ;
					//现金券已经过期---并且限制日期在礼券结束日期前
					if((limitdate.before(enddate) && rightTime.after(limitdate))|| (limitdate.after(enddate) && rightTime.after(enddate))){
						flag = 2; //设置现金券已经过期标识
						endDate = new SimpleDateFormat("yyyy-MM-dd").format((DateUtils.parseDate(DateUtils.getAfterDay(assignedtime, daysLimit),DateUtils.DAY_FROMAT)));
						result.put("endDate", endDate);
						result.put("flag", flag);
						result.put("ajaxResponse", ajaxResponse);
						return result;
					}else{
						endDate = new SimpleDateFormat("yyyy年MM月dd日").format((DateUtils.parseDate(DateUtils.getAfterDay(assignedtime, daysLimit), DateUtils.DAY_FROMAT)));
					}
				}else{
					Date begindate = DateUtils.parseDate(cashCouponMap.get("BEGINDATE").toString(), DateUtils.CURRENTTIME_FORMAT) ;
					//现金券还未到使用日期
					if (begindate.after(rightTime)) {
						flag = 9;//设置现金券未到使用日期标示
						result.put("flag", flag);
						result.put("ajaxResponse", ajaxResponse);
						return result;
					}
					//现金券已经过期--没有限制日期
					if( rightTime.after(enddate)){
						flag = 2;//设置现金券已经过期标识
						endDate = new SimpleDateFormat("yyyy-MM-dd").format((DateUtils.parseDate(cashCouponMap.get("ENDDATE").toString(),DateUtils.DAY_FROMAT)));
						result.put("endDate", endDate);
						result.put("flag", flag);
						result.put("ajaxResponse", ajaxResponse);
						return result;
					}else{
						endDate = new SimpleDateFormat("yyyy年MM月dd日").format((DateUtils.parseDate(cashCouponMap.get("ENDDATE").toString(), DateUtils.DAY_FROMAT)));
					}
				}
				result.put("endDate", endDate);
				//6.特殊商品适用类型--可用商品
				if(null != cashCouponMap.get("SPECIALPRODUCTTYPE") && 1 == Integer.valueOf(cashCouponMap.get("SPECIALPRODUCTTYPE").toString())){
					//6.1.判断礼券的使用范围
					if(null != cashCouponMap.get("USESCOPE") && !cashCouponMap.get("USESCOPE").toString().contains(String.valueOf(2))){
						flag = 3;   //设置现金券不适用于228主网站标识
						result.put("flag", flag);
						result.put("ajaxResponse", ajaxResponse);
						return result;
					}
					//6.2.判断分站是否支持礼券使用--如果适用的分站不为空
					if(null != cashCouponMap.get("USEFCONFIG")){
						String usefconfigs = cashCouponMap.get("USEFCONFIG").toString();
						//如果分站不支持适用礼券
						if(!usefconfigs.contains(fconfigId)){
							flag = 4; //设置分站不支持适用现金券标识
							result.put("flag", flag);
							result.put("ajaxResponse", ajaxResponse);
							return result;
						}
					}
					//6.3判断商品是否支持使用礼券
					if (null != cashCouponMap.get("SPECIALPRODUCTIDS") && !StringUtil.isEmpty(cashCouponMap.get("SPECIALPRODUCTIDS").toString())) {// 不允许使用礼券的商品的ID
						String[] productids = productId.split(",");
						for (String productid : productids) {
							if (cashCouponMap.get("SPECIALPRODUCTIDS").toString().contains(productid)) {
								flag = 5;// 商品ID属于不允许使用礼券的商品
								result.put("flag", flag);
								result.put("ajaxResponse", ajaxResponse);
								return result;													
							}
						}
					}
					//6.4判断商品是否支持适用分类
					if (null != cashCouponMap.get("USEPRODUCTTYPE")) { // 不允许使用礼券的商品适用分类
						String[] productids = productId.split(",");
						for (String productid : productids) {
							cashParams.put("productId", productid);
							Map<String, Object> product = null;
							try {
								product = orderService.getProductAll(cashParams);
							} catch (Exception e) {
								log.error("查询商品异常{}",cashParams,e);
								return null;
							}
							if (!cashCouponMap.get("USEPRODUCTTYPE").toString().contains(product.get("producttypeaid1").toString())) {
								flag = 8;// 商品ID属于不允许使用礼券的适用分类
								result.put("flag", flag);
								result.put("ajaxResponse", ajaxResponse);
								return result;													
							}
						}
					}
					//判断商品
				//7.特殊商品适用类型--不可用商品
				}else{
					//7.3判断商品是否支持使用礼券
					if (null != cashCouponMap.get("SPECIALPRODUCTIDS") && !StringUtil.isEmpty(cashCouponMap.get("SPECIALPRODUCTIDS").toString())) {// 不允许使用礼券的商品的ID
						String[] productids = productId.split(",");
						for (String productid : productids) {
							if (!cashCouponMap.get("SPECIALPRODUCTIDS").toString().contains(productid)) {
								//7.1.判断礼券的使用范围
								if(null != cashCouponMap.get("USESCOPE") && cashCouponMap.get("USESCOPE").toString().contains(String.valueOf(2))){
									flag = 3;   //设置现金券不适用于228主网站标识
									result.put("flag", flag);
									result.put("ajaxResponse", ajaxResponse);
									return result;
								}
								//7.2.判断分站是否支持礼券使用--如果适用的分站不为空
								if(null != cashCouponMap.get("USEFCONFIG")){
									String[] customerCashUseFconfigs = cashCouponMap.get("USEFCONFIG").toString().split(",");
									for (int i = 0; i < customerCashUseFconfigs.length; i++) {
										if (customerCashUseFconfigs[i].replace(" ","").equals(fconfigId.toString())) {
											//如果分站不支持适用礼券
											flag = 4; //设置分站不支持适用现金券标识
											result.put("flag", flag);
											result.put("ajaxResponse", ajaxResponse);
											return result;
										}
									}						
								}else{
									//不可用分站为空，说明后台勾选的全部，所以不可用于购买当前分站的商品
									flag = 4; //设置分站不支持适用现金券标识
									result.put("flag", flag);
									result.put("ajaxResponse", ajaxResponse);
									return result;									
								}
								//7.4判断商品是否支持适用分类
								String[] productidss = productId.split(",");
								for (String productida : productidss) {
									cashParams.put("productId", productida);
									Map<String, Object> product = null;
									try {
										product = orderService.getProductAll(cashParams);
									} catch (Exception e) {
										log.error("查询商品异常{}",cashParams,e);
										return null;
									}
									if (null != cashCouponMap.get("USEPRODUCTTYPE") && cashCouponMap.get("USEPRODUCTTYPE").toString().contains(product.get("producttypeaid1").toString())) {
										flag = 8;// 商品ID属于不允许使用礼券的适用分类
										result.put("flag", flag);
										result.put("ajaxResponse", ajaxResponse);
										return result;													
									}
								}											
							}
						}
					}else {
						//7.1.判断礼券的使用范围
						if(null != cashCouponMap.get("USESCOPE") && cashCouponMap.get("USESCOPE").toString().contains(String.valueOf(2))){
							flag = 3;   //设置现金券不适用于228主网站标识
							result.put("flag", flag);
							result.put("ajaxResponse", ajaxResponse);
							return result;
						}
						//7.2.判断分站是否支持礼券使用--如果适用的分站不为空
						if(null != cashCouponMap.get("USEFCONFIG")){
							String[] customerCashUseFconfigs = cashCouponMap.get("USEFCONFIG").toString().split(",");
							for (int i = 0; i < customerCashUseFconfigs.length; i++) {
								if (customerCashUseFconfigs[i].replace(" ","").equals(fconfigId.toString())) {
									//如果分站不支持适用礼券
									flag = 4; //设置分站不支持适用现金券标识
									result.put("flag", flag);
									result.put("ajaxResponse", ajaxResponse);
									return result;
								}
							}						
						}else{
							//不可用分站为空，说明后台勾选的全部，所以不可用于购买当前分站的商品
							flag = 4; //设置分站不支持适用现金券标识
							result.put("flag", flag);
							result.put("ajaxResponse", ajaxResponse);
							return result;									
						}
						//7.4判断商品是否支持适用分类
						String[] productidss = productId.split(",");
						for (String productida : productidss) {
							cashParams.put("productId", productida);
							Map<String, Object> product = null;
							try {
								product = orderService.getProductAll(cashParams);
							} catch (Exception e) {
								log.error("查询商品异常{}",cashParams,e);
								return null;
							}
							if (null != cashCouponMap.get("USEPRODUCTTYPE") && cashCouponMap.get("USEPRODUCTTYPE").toString().contains(product.get("producttypeaid1").toString())) {
								flag = 8;// 商品ID属于不允许使用礼券的适用分类
								result.put("flag", flag);
								result.put("ajaxResponse", ajaxResponse);
								return result;													
							}
						}						
					}

				}
				// 8.判断是否满足最低消费金额 现金券金额
				if (null != cashCouponMap.get("LOWEST")) {
					Double lowestExpense = Double.valueOf(cashCouponMap.get("LOWEST").toString());
					if (Double.parseDouble(subTotalVal) < lowestExpense) {
						flag = 6;
						result.put("lowestExpense", lowestExpense);
						result.put("flag", flag);
						result.put("ajaxResponse", ajaxResponse);
						return result;			
					}
				}
				// 9.判断礼券是否已经存在
				if (0 == isreuse && null != customer && null != cashCouponMap.get("CUSTOMERSID") && cashCouponMap.get("CUSTOMERSID").toString().equals(customer.get("customersId").toString())) {
					flag = 7;
					result.put("flag", flag);
					result.put("ajaxResponse", ajaxResponse);
					return result;	
				}
				result.put("ticket", cashCouponMap.get("PARVALUE").toString());
				result.put("cashcouponinfoid", cashCouponMap.get("CASHCOUPONINFOID").toString());
			}else{
				flag = -2;
			}
		} catch (Exception e) {
			log.warn("判断现金券使用逻辑异常{}",cashParams,e);
			flag = -1;
		}
		result.put("flag", flag);
		result.put("ajaxResponse", ajaxResponse);
		return result;
	}
	
	/**
	 * @description 功能描述: 是否支持货到付款
	 * @author      作 者: 于旺
	 * @param       参数: String productId 商品ID,String addressId 用户配送地址ID,String cityId商品所在城市ID
	 * @return      返回类型: Map<String,Object>
	 * @createdate  建立日期: 2015年10月23日14:00:59
	 */
	@RequestMapping(value = "/isCashOnDelivery" ,method = RequestMethod.POST)
	public @ResponseBody Map<String,Object> isCashOnDelivery(String productId,String addressId,String cityId,String playDate,HttpSession session) {
		Map<String,Object> returnMap = new HashMap<>();
		returnMap.put("flag", 0);
		//是否支持货到付款     0不支持 1 支持
		if (!StringUtils.isEmpty(productId) && !StringUtils.isEmpty(addressId) && !StringUtils.isEmpty(cityId)) {
			Map<String, Object> cashOnParam = new HashMap<String, Object>();
			cashOnParam.put("productId", productId);
			cashOnParam.put("addressIdCustomersId", addressId);
			cashOnParam.put("customersId", ServletUtil.getCustomerId(session));
			try {	
				//7.支付限制总开关
				Integer isCashDisAll = orderService.isCashDisAll(cashOnParam);
				if (isCashDisAll.intValue() == 0) {
					return returnMap;    //设置不支持货到付款标识
				}
				
				//查询商品信息
				Map<String, Object> product = orderService.getProductAll(cashOnParam);
				if (!StringUtil.isEmpty(product.get("psxx"))) {
					String psxx = product.get("psxx").toString();
					//1.商品配置不支持
					if (psxx.contains("3")) {
						return returnMap;    //设置不支持货到付款标识
					}
				}
				
				//2.演出前六天不支持
				SimpleDateFormat formatter = new SimpleDateFormat(DateUtils.DAY_FROMAT);      
				Date rightDate = new Date();                         //获取服务器当前时间      
				String nowDate = formatter.format(rightDate);        //格式化时间
				Integer differTime  = DateUtils.getDiffDays(nowDate,playDate);//现在时间与演出开始的时间差
				if(differTime <= 5) {
					return returnMap;    //设置不支持货到付款标识
				}
				//3.配送地址和商品分站不在一起，也就是非同城，不支持
				Map<String, Object> cusaddres = addressService.findAddressCustomerById(cashOnParam);
				String addCityId = cusaddres.get("cityId").toString();
				if (!addCityId.equals(cityId)) {
					return returnMap;    //设置不支持货到付款标识
				}
				//4.配送地址，也就是四级区域配置不支持
				String addCodeId =cusaddres.get("codeId").toString();
				cashOnParam.put("codeId", addCodeId);
				Map<String, Object> addCode = addressService.findCodeById(cashOnParam);
				//是否支持货到付款，1、支持；0、不支持
				if (addCode != null) {
					String supportHdfk = addCode.get("supporthdfk").toString();
					if (supportHdfk.equals("0")) {
						return returnMap; // 设置不支持货到付款标识
					}
				}
				//5.选座商品，不支持货到付款
				Object path = product.get("path");
				if (!StringUtil.isEmpty(path)) {
					return returnMap;    //设置不支持货到付款标识
				}
				//6.支付限制货到付款
				Integer isCashDis = orderService.isCashDis(cashOnParam);
				if (isCashDis.intValue() == 0) {
					return returnMap;    //设置不支持货到付款标识
				}
			} catch (Exception e) {
				log.error("判断是否支持货到付款异常{}",cashOnParam,e);
				return returnMap;    //设置不支持货到付款标识
			}
		}else {
			return returnMap;    //设置不支持货到付款标识
		}
		returnMap.put("flag", 1);
		return returnMap;
	}
	/**
	 * 
	 * @description  功能描述: 查询该身份证是否购买过此商品
	 * @author 	              作       者: 于旺
	 * @param        参       数: 商品id,身份证号码
	 * @return       返回类型: String 
	 * @createdate   建立日期: 2015年10月25日14:58:02
	 */
	@RequestMapping(value = "/findCardnoisExistNew",method = RequestMethod.POST)
	public  @ResponseBody Map<String,Object> findCardnoisExistNew(String productId, String cardno,String cardtype){
		Map<String,Object> result = new HashMap<String,Object>();
		String flag= "0";  //校验身份证 0不可用 1 可用
		Object msg = "查询异常";
		//如果证件或商品ID或者证件类型为空，则直接返回不可用
		if (StringUtil.isEmpty(productId) || StringUtil.isEmpty(cardtype)) {
			result.put("flag", flag);
			result.put("msg", msg);
			return result;
		}
		try {
			String verifyCode = cardtype+"^"+cardno+"^"+productId;
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("o['verifyCode']",verifyCode);
			Map<String,Object> cardnoMap = saveOrderService.getCardnoBuyProduct(paramMap);
			log.info("校验证件接口返回结果为:{}",cardnoMap);
			if (cardnoMap != null && !StringUtil.isEmpty(cardnoMap.get("code"))) {
				String code = cardnoMap.get("code").toString();
				if (!"0".equals(code)) {
					flag = "0" ;
					msg = CardResult.getMsg(code);
				}else{
					flag = "1";
					msg = "";
				}
			}else {
				flag = "0";
			}			
		} catch (Exception e) {
			flag = "0";
		}
		
		result.put("flag", flag);
		result.put("msg", msg);
		return result;
	}	
	
	/**
	 * 
	 * @description  功能描述: 验证电子钱包密码是否正确
	 * @author 	              作       者: 于旺
	 * @param        参       数: 当前登陆用户的预存款密码
	 * @return       返回类型: Integer 
	 * @createdate   建立日期: 2015年10月29日15:20:08
	 */
	@RequestMapping(value = "/findRenewal")
	public @ResponseBody Integer findRenewal(String password,String customerId){
		Integer flag = 0 ;//是否正确  0否 1是
		//用户ID或者预存款密码为空,验证不通过
		if (StringUtil.isEmpty(customerId)||StringUtil.isEmpty(password)) {
			return 0;
		}
		Map<String, Object> renewalParam = new HashMap<String, Object>();
		renewalParam.put("password",password);
		renewalParam.put("customerId",customerId);
		try {
			flag = orderService.findRenewal(renewalParam);
		} catch (Exception e) {
			flag = 0 ;
		}
		return flag;
	}	
	
	/**
	* @Title: getCodeSPDB
	* @Description: 浦发银行获取验证码
	* @param String
	* @author : 于旺
	* @date   :2016年3月31日14:27:02
	* @return :String
	*/
	@RequestMapping(value = "/getCodeSPDB" ,method = RequestMethod.POST)
	public @ResponseBody String getCodeSPDB(String bank_cardno) {
		if (StringUtil.isEmpty(bank_cardno)) {
			return null;
		}
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("bank_cardno", bank_cardno);
		String result = payService.getCodeSPDB(paramMap);
		if (StringUtil.isEmpty(result)) {
			return null;
		}
		log.info("验证码发送成功，银行卡号:{}返回码:{}",bank_cardno,result);
		return result;
	}
	
	/**
	* @Title: toSignSPDB
	* @Description: 浦发银行签约 1 |解约 2 
	* @param String
	* @author : 于旺
	* @date   :2016年3月31日14:26:25
	* @return :String
	*/
	@RequestMapping(value = "/toSignSPDB" ,method = RequestMethod.POST)
	public @ResponseBody String toSignSPDB(String bank_cardno, String cvv2,String signingFlag,String customerId) {
		if (StringUtil.isEmpty(bank_cardno) || StringUtil.isEmpty(cvv2) ||StringUtil.isEmpty(signingFlag) || StringUtil.isEmpty(customerId)) {
			return null;
		}
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("bank_cardno", bank_cardno);
		paramMap.put("cvv2", cvv2);
		paramMap.put("signingFlag", signingFlag);
		paramMap.put("customer_id", customerId);
		String result = payService.toSignSPDB(paramMap);
		if (StringUtil.isEmpty(result)) {
			return null;
		}
		if (signingFlag.equals("1")) {
			log.info("签约成功，银行卡号:{}返回码:{}",bank_cardno,result);
		}
		if (signingFlag.equals("2")) {
			log.info("解约成功，银行卡号:{}返回码:{}",bank_cardno,result);
		}		
		
		return result;
	}
	
	/**
	* @Title: getCardno
	* @Description: 通过用户ID获取绑定的浦发银行卡号
	* @param String
	* @author : 于旺
	* @date   :2016年4月11日14:17:44
	* @return :String
	*/
	@RequestMapping(value = "/getCardno" ,method = RequestMethod.POST)
	public @ResponseBody String getCardno(String customerId) {
		if (StringUtil.isEmpty(customerId)) {
			return null;
		}
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("customer_id", customerId);
		String result = payService.getCardno(paramMap);
		log.info("获取用户卡号:{}用户ID：{}",result,customerId);
		if (StringUtil.isEmpty(result)) {
			return null;
		}
		return result;
	}
}

